#include "bookunzipper.h"
#include <QDir>
#include "quazip.h"
#include "quazipfile.h"
#include "quazip_global.h"
#include <QImageReader>
#include "bookitemlist.h"

BookUnzipper::BookUnzipper()
{
    m_cancel = false;
}

void BookUnzipper::run()
{
    int count = 1;
    QString text("Opening page %1");
    BookItemList::ErrorCodes code = BookItemList::NoError;

    QDir path(PRIVATE_BOOKDIR);
    path.rmpath(PRIVATE_BOOKDIR);

    if(path.mkpath(PRIVATE_BOOKDIR)){
        QuaZip zip(m_archiveName);

        if(zip.open(QuaZip::mdUnzip)){
            int total = zip.getEntriesCount();

            QuaZipFile file(&zip);
            bool running = zip.goToFirstFile();
            while(running){
                if(file.open(QIODevice::ReadOnly)){

                    QFile outfile(PRIVATE_BOOKDIR_EXTRACTED+"/"+zip.getCurrentFileName());

                    int end = outfile.fileName().lastIndexOf('/');
                    if(end >0){
                        QString dname = outfile.fileName().mid(0,end);                        
                        QDir d(dname);
                        d.mkpath(dname);
                    }

                    if(outfile.open(QIODevice::ReadWrite)){
                        qint64 totalbytes = file.bytesAvailable();
                        qint64 amount = 0;
                        int block = 4096;
                        while(amount<totalbytes){
                            QByteArray arr;
                            arr = file.read(block);

                            if(arr.length()>0){
                                amount+=arr.length();
                                outfile.write(arr);
                                outfile.flush();
                            }
                        }
                    }else{
                        if(QFile::exists(outfile.fileName()) && outfile.size() > 0 )
                            code = BookItemList::NoError;
                        else
                            code = BookItemList::ZipBroken;
                    }
                    outfile.close();
                }
                file.close();
                emit this->openedZipPage(count,total,text);
                count++;
                running = zip.goToNextFile();
                if(running && m_cancel){
                    running = !m_cancel;
                }
            }
            zip.close();            
        }else{
            code = BookItemList::ZipBroken;
        }
    }else{
        code = BookItemList::NotEnoughSpace;
    }
    emit this->extractFinished(code);
}

void BookUnzipper::setArchiveName(QString text)
{
    m_archiveName = text;
}

void BookUnzipper::cancelRun()
{
    m_cancel = true;
}
